//
//  BIZBusinessPremisesDetailVC.m
//  biz
//
//  Created by 小龙 on 2017/4/6.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "BIZBusinessPremisesDetailVC.h"
//#import "BIZBusinessPremissDetailTableViewContrller.h"
#import "BIZBusinessPressDetailFirstCell.h"
#import "BIZBusinessPressDetailSecondCell.h"
#import "BIZBusinessPressDetailIntroCell.h"
#import "BIZBusinessPressDetailHonorCell.h"
#import "BIZBusinessPressDetailAchievementCell.h"
#import "CWStarRateView.h"
#import "BIZActivityDetailVC.h"
#import "BIZActivityModel.h"
#import "BIZActivityForecastCell.h"


typedef NS_ENUM(NSUInteger, CTCCurrentPageType) {
    CTCCurrentPageTypeHome = 1,
    CTCCurrentPageTypeActivityAdvance,
    CTCCurrentPageTypeFeatureService
};

@interface BIZBusinessPremisesDetailVC ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIButton *consultBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *headView;
@property (weak, nonatomic) IBOutlet UIButton *homePageBtn;
@property (weak, nonatomic) IBOutlet UIButton *activitiesAdvanceBtn;
@property (weak, nonatomic) IBOutlet UIButton *featureServicesBtn;
/** 选择的按钮 */
@property (nonatomic, strong) UIButton *selectedBtn;
@property (weak, nonatomic) IBOutlet UIView *homeLineView;
@property (weak, nonatomic) IBOutlet UIView *activitiesLineView;
@property (weak, nonatomic) IBOutlet UIView *featureLineView;

/** 当前页面展示类型 */
@property (nonatomic, assign) CTCCurrentPageType currentPageType;
@property (weak, nonatomic) IBOutlet UIImageView *logoImageView;
@property (weak, nonatomic) IBOutlet UILabel *officeNameLabel;
@property (weak, nonatomic) IBOutlet BIZStarView *starView;
@property (weak, nonatomic) IBOutlet UILabel *gradeLabel;

@property (nonatomic, strong) BIZOfficeModel *officeDetailModel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *starViewWidthLayout;

@property (nonatomic, strong) NSMutableArray *activityArr;
@property (nonatomic, assign) NSInteger thirdLastID;

@end

@implementation BIZBusinessPremisesDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    DeLog(@"viewDidLoad: %@",self.consultBtn);
    
    self.thirdLastID = 1;
    
    
    [self setupUI];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"BIZActivityForecastCell" bundle:nil] forCellReuseIdentifier:@"BIZActivityForecastCell"];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNew)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    
    [self getOfficeDetailModelData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//     self.automaticallyAdjustsScrollViewInsets = NO;
    DeLog(@"viewWillAppear: %@",self.consultBtn);
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    //去除导航条透明后导航条下的黑线
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.automaticallyAdjustsScrollViewInsets = YES;
//    self.automaticallyAdjustsScrollViewInsets = YES;
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:COLOR_NAVBAR_BLUE]
                                                  forBarMetrics:UIBarMetricsDefault];
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    DeLog(@"viewDidAppear: %@",self.consultBtn);
}


- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    DeLog(@"viewWillLayoutSubviews: %@",self.consultBtn);
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
//    self.starViewWidthLayout.constant = self.starView.frame.size.width;
    DeLog(@"viewDidLayoutSubviews: %@",self.consultBtn);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.currentPageType ==  CTCCurrentPageTypeHome) {
         return 5;
    } else if (self.currentPageType == CTCCurrentPageTypeActivityAdvance) {
         return self.activityArr.count;
    }
    
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.currentPageType == CTCCurrentPageTypeActivityAdvance) {
        BIZActivityForecastCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BIZActivityForecastCell" forIndexPath:indexPath];
        cell.activityModel = self.activityArr[indexPath.row];
        
        return cell;
    }
    
    if (indexPath.row == 0) {
        BIZBusinessPressDetailFirstCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BIZBusinessPressDetailFirstCell" forIndexPath:indexPath];
        
        cell.customTitleLabel.text = [NSString stringWithFormat:@"事务所名称：%@", self.officeDetailModel.name];
        return cell;
    }
    
    if (indexPath.row == 1) {
        BIZBusinessPressDetailSecondCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BIZBusinessPressDetailSecondCell" forIndexPath:indexPath];
        cell.locationLabel.text = [NSString stringWithFormat:@"所在地区：%@", self.officeDetailModel.city];
        cell.adeptFieldLabel.text = [NSString stringWithFormat:@"擅长领域：%@", self.officeDetailModel.coreBusi];
        return cell;
        
    }
    
    
    if (indexPath.row == 2) {
        BIZBusinessPressDetailIntroCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BIZBusinessPressDetailIntroCell" forIndexPath:indexPath];
        cell.introductionLabel.text = self.officeDetailModel.introduction;
        
        return cell;
        
    }
    
    
    if (indexPath.row == 3) {
        BIZBusinessPressDetailHonorCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BIZBusinessPressDetailHonorCell" forIndexPath:indexPath];
        cell.photoGroupStr = self.officeDetailModel.style;
        return cell;
        
    }
    
    BIZBusinessPressDetailAchievementCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BIZBusinessPressDetailAchievementCell" forIndexPath:indexPath];
    cell.achievementLabel.text = self.officeDetailModel.researchResults;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.currentPageType != CTCCurrentPageTypeActivityAdvance) {
        return;
    }
    
    BIZActivityDetailVC *vc = [[BIZActivityDetailVC alloc]init];
    vc.activityModel = self.activityArr[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)switchBtnClick:(UIButton *)sender {
    
    
    if (sender.tag  == self.selectedBtn.tag) {
        return;
    }
    
    if (sender.tag == 103) {
        [MBProgressHUD showTipMessageInWindow:@"敬请期待"];
        return;
    }
    
    self.selectedBtn.selected = NO;
    self.selectedBtn = sender;
    self.selectedBtn.selected = YES;
    
    if (sender.tag == 101) {
        
        [self.homePageBtn setTitleColor:HEXCOLOR(0x2E8CE5)  forState:UIControlStateNormal];
        [self.activitiesAdvanceBtn setTitleColor:HEXCOLOR(0x666666)  forState:UIControlStateNormal];
        [self.featureServicesBtn setTitleColor:HEXCOLOR(0x666666)  forState:UIControlStateNormal];
        
        [self.homePageBtn setImage:[UIImage imageNamed:@"(编组)副本"] forState:UIControlStateNormal];
        [self.activitiesAdvanceBtn setImage:[UIImage imageNamed:@"预告"] forState:UIControlStateNormal];
        [self.featureServicesBtn setImage:[UIImage imageNamed:@"特色"] forState:UIControlStateNormal];
        self.homeLineView.hidden = NO;
        self.activitiesLineView.hidden = YES;
        self.featureLineView.hidden = YES;
        self.currentPageType = CTCCurrentPageTypeHome;
        
        [self getOfficeDetailModelData];
        
        
    } else if (sender.tag == 102) {
        [self.homePageBtn setTitleColor:HEXCOLOR(0x666666)  forState:UIControlStateNormal];
        [self.activitiesAdvanceBtn setTitleColor:HEXCOLOR(0x2E8CE5)  forState:UIControlStateNormal];
        [self.featureServicesBtn setTitleColor:HEXCOLOR(0x666666)  forState:UIControlStateNormal];
        
        [self.homePageBtn setImage:[UIImage imageNamed:@"(编组)副本2"] forState:UIControlStateNormal];
        [self.activitiesAdvanceBtn setImage:[UIImage imageNamed:@"yugaos"] forState:UIControlStateNormal];
        [self.featureServicesBtn setImage:[UIImage imageNamed:@"特色"] forState:UIControlStateNormal];
        self.homeLineView.hidden = YES;
        self.activitiesLineView.hidden = NO;
        self.featureLineView.hidden = YES;
        self.currentPageType = CTCCurrentPageTypeActivityAdvance;
        
        
        [self loadNew];
        
    } else {
      
        
        [self.homePageBtn setTitleColor:HEXCOLOR(0x666666)  forState:UIControlStateNormal];
        [self.activitiesAdvanceBtn setTitleColor:HEXCOLOR(0x666666)  forState:UIControlStateNormal];
        [self.featureServicesBtn setTitleColor:HEXCOLOR(0x2E8CE5)  forState:UIControlStateNormal];
        
        [self.homePageBtn setImage:[UIImage imageNamed:@"(编组)副本2"] forState:UIControlStateNormal];
        [self.activitiesAdvanceBtn setImage:[UIImage imageNamed:@"预告"] forState:UIControlStateNormal];
        [self.featureServicesBtn setImage:[UIImage imageNamed:@"ssss"] forState:UIControlStateNormal];
        self.homeLineView.hidden = YES;
        self.activitiesLineView.hidden = YES;
        self.featureLineView.hidden = NO;
        self.currentPageType = CTCCurrentPageTypeFeatureService;

    }
    
    
    
}

- (void)setupUI {
    self.view.backgroundColor = HEXCOLOR(0xF9F9F9);
    
    [self.homePageBtn setButtonImageTitleStyle:ButtonImageTitleStyleTop padding:5];
    [self.activitiesAdvanceBtn setButtonImageTitleStyle:ButtonImageTitleStyleTop padding:5];
    [self.featureServicesBtn setButtonImageTitleStyle:ButtonImageTitleStyleTop padding:5];
    self.selectedBtn = self.homePageBtn;
    self.currentPageType = CTCCurrentPageTypeHome;
    self.tableView.estimatedRowHeight = 300;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.tableHeaderView = self.headView;
    self.tableView.tableHeaderView.height = 234;

    [self.tableView registerNib:[UINib nibWithNibName:@"BIZBusinessPressDetailFirstCell" bundle:nil] forCellReuseIdentifier:@"BIZBusinessPressDetailFirstCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"BIZBusinessPressDetailSecondCell" bundle:nil] forCellReuseIdentifier:@"BIZBusinessPressDetailSecondCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"BIZBusinessPressDetailIntroCell" bundle:nil] forCellReuseIdentifier:@"BIZBusinessPressDetailIntroCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"BIZBusinessPressDetailHonorCell" bundle:nil] forCellReuseIdentifier:@"BIZBusinessPressDetailHonorCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"BIZBusinessPressDetailAchievementCell" bundle:nil] forCellReuseIdentifier:@"BIZBusinessPressDetailAchievementCell"];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat reOffset = scrollView.contentOffset.y + (App_Frame_Height - 64) * 0.2;
    CGFloat alpha = reOffset / ((App_Frame_Height - 64) * 0.2);
    if (alpha <= 1)//下拉永不显示导航栏
    {
        alpha = 0;
    }
    else//上划前一个导航栏的长度是渐变的
    {
        alpha -= 1;
        self.title = self.officeModel.name;
    }
    // 设置导航条的背景图片 其透明度随  alpha 值 而改变 JSBRGBColor(76, 92, 108)
    UIImage *image = [self imageWithColor:[UIColor colorWithRed:46/255.0 green:140/255.0 blue:229/255.0 alpha:alpha]];
    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
}


/// 使用颜色填充图片
- (UIImage *)imageWithColor:(UIColor *)color
{
    // 描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    
    return theImage;
}

- (void)getOfficeDetailModelData {
    
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kBusinessPremisesDetailUrl
           parameters:@{@"uuid":self.officeModel.uuid}
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  DeLog(@"事务所详情responseObject：%@",responseObject);
                  [self stopRefresh];
                  BIZOfficeModel *model = [BIZOfficeModel yy_modelWithJSON:responseObject[@"data"]];
                  if ([responseObject[@"code"] integerValue] == 1) {
                      [MBProgressHUD hideHUD];
                      self.officeDetailModel = model;
                      
                      self.title = self.officeDetailModel.name;
                      self.officeNameLabel.text = self.officeDetailModel.name;
                      [SDWebImageTool imageView:self.logoImageView
                                      imageName:self.officeDetailModel.logImg placeHolder:@"default-head" showProgress:YES];
                      NSString *str = [NSString stringWithFormat:@"综合评分：%.1f分", self.officeDetailModel.score];
                      NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:str];
                      [attrStr addAttribute:NSForegroundColorAttributeName
                                      value:[UIColor whiteColor]
                                      range:NSMakeRange(0, 5)];
                      
                      self.gradeLabel.attributedText = attrStr;
//                      self.starView.imageNum = 3;
                      
                      [self.tableView reloadData];
                  } else {
                      [MBProgressHUD showErrorMessage:responseObject[@"des"]];
                      if ([responseObject[@"code"] integerValue] == 2) {
                          BIZLoginViewController *vc = [BIZLoginViewController viewControllerFromStoryboard];
                          MPWeakSelf(self);
                          vc.loginSuccessBlock = ^(){
                              [weakself getOfficeDetailModelData];
                          };
                          [self presentViewController:vc animated:YES completion:nil];
                      }
                  }
                  
              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  DeLog(@"事务所详情error：%@",error);
                  [self stopRefresh];
                  if (![AFNetworkReachabilityManager sharedManager].isReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }

              }];
}



- (void)loadNew {
    
    if (self.currentPageType == CTCCurrentPageTypeHome) {
        self.officeDetailModel = nil;
        [self getOfficeDetailModelData];
        [self.tableView.mj_footer resetNoMoreData];
        
    } else if (self.currentPageType == CTCCurrentPageTypeActivityAdvance) {
        self.thirdLastID = 1;
        [self.activityArr removeAllObjects];
        [self.tableView.mj_footer resetNoMoreData];
        [self loadActivityListData];
    }
}

- (void)loadMore {
    if (self.currentPageType == CTCCurrentPageTypeHome) {
        [self getOfficeDetailModelData];
        
    } else if (self.currentPageType == CTCCurrentPageTypeActivityAdvance) {
        [self loadActivityListData];
        
    }
}


- (void)loadActivityListData {
    NSMutableDictionary *paramDic = [NSMutableDictionary dictionary];
    paramDic[@"pageIndex"] = @(self.thirdLastID);
    paramDic[@"pageEnd"] = @(self.thirdLastID+9);
    paramDic[@"uuid"] = self.officeModel.uuid;
    
    [MBProgressHUD showAnimationHUD];
    
    [RequestTool POST:kActivityListUrl parameters:paramDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"事务所详情的活动+++responseObject:%@",responseObject);
        [self stopRefresh];
        BIZActivityListModel *listModel = [BIZActivityListModel yy_modelWithJSON:responseObject];
        if (listModel.code == 1) {
            [MBProgressHUD hideHUD];
            if (!listModel.activityArr.count) {
                self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
                
            }
            
            [self.activityArr addObjectsFromArray:listModel.activityArr];
            self.thirdLastID += self.activityArr.count;
            [self.tableView reloadData];
            
        } else {
            [MBProgressHUD showErrorMessage:listModel.des];
            if (listModel.code == 2) {
                BIZLoginViewController *vc = [BIZLoginViewController viewControllerFromStoryboard];
                MPWeakSelf(self);
                vc.loginSuccessBlock = ^(){
                    [weakself loadNew];
                };
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error:%@",error);
        [self stopRefresh];
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
        
    }];
    
}

- (void)stopRefresh {
    !self.tableView.mj_header.isRefreshing ? : self.tableView.mj_header.endRefreshing;
    !self.tableView.mj_footer.isRefreshing ? : self.tableView.mj_footer.endRefreshing;
    
}

- (NSMutableArray *)activityArr {
    if (!_activityArr) {
        _activityArr = [NSMutableArray array];
    }
    
    return _activityArr;
}



@end
